using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;
using System.Security.Cryptography;
using System.Text;

namespace community.Controllers
{
    /// <summary>
    /// 查询居民列表的参数
    /// </summary>
    public class ResidentQueryDTO
    {
        /// <summary>
        /// 居民姓名（支持模糊查询）
        /// </summary>
        public string? Name { get; set; }

        /// <summary>
        /// 联系电话（支持模糊查询）
        /// </summary>
        public string? Phone { get; set; }

        /// <summary>
        /// 身份证号（支持模糊查询）
        /// </summary>
        public string? IdCard { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新居民的数据模型
    /// </summary>
    public class ResidentDTO
    {
        /// <summary>
        /// 居民姓名
        /// </summary>
        [Required(ErrorMessage = "姓名不能为空")]
        public string Name { get; set; }

        /// <summary>
        /// 联系电话
        /// </summary>
        [Required(ErrorMessage = "联系电话不能为空")]
        [Phone(ErrorMessage = "请输入有效的电话号码")]
        public string Phone { get; set; }

        /// <summary>
        /// 身份证号
        /// </summary>
        [Required(ErrorMessage = "身份证号不能为空")]
        [StringLength(18, MinimumLength = 18, ErrorMessage = "身份证号必须是18位")]
        public string IdCard { get; set; }

        /// <summary>
        /// 性别（男/女）
        /// </summary>
        [Required(ErrorMessage = "性别不能为空")]
        public string Gender { get; set; }

        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime? BirthDate { get; set; }

        /// <summary>
        /// 居住地址
        /// </summary>
        [Required(ErrorMessage = "居住地址不能为空")]
        public string Address { get; set; }

        /// <summary>
        /// 关联房屋ID
        /// </summary>
        public int? HouseId { get; set; }
    }

    /// <summary>
    /// 修改密码请求模型
    /// </summary>
    public class ResidentChangePasswordDTO
    {
        /// <summary>
        /// 原密码
        /// </summary>
        [Required(ErrorMessage = "原密码不能为空")]
        public string OldPassword { get; set; }

        /// <summary>
        /// 新密码
        /// </summary>
        [Required(ErrorMessage = "新密码不能为空")]
        [StringLength(100, MinimumLength = 6, ErrorMessage = "密码长度必须在6-100个字符之间")]
        public string NewPassword { get; set; }
    }

    /// <summary>
    /// 居民信息管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ResidentController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ResidentController(ApplicationDbContext context)
        {
            _context = context;
        }

        private string HashPassword(string password)
        {
            using (var sha256 = SHA256.Create())
            {
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
                return Convert.ToBase64String(hashedBytes);
            }
        }

        /// <summary>
        /// 获取居民列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>居民列表和总数</returns>
        /// <response code="200">成功获取居民列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetResidents([FromQuery] ResidentQueryDTO query)
        {
            var residents = _context.Residents.AsQueryable();

            if (!string.IsNullOrEmpty(query.Name))
                residents = residents.Where(r => r.Name.Contains(query.Name));
            
            if (!string.IsNullOrEmpty(query.Phone))
                residents = residents.Where(r => r.Phone.Contains(query.Phone));
            
            if (!string.IsNullOrEmpty(query.IdCard))
                residents = residents.Where(r => r.IdCard.Contains(query.IdCard));

            var total = await residents.CountAsync();

            var pagedResidents = await residents
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .ToListAsync();

            return Ok(new {
                Total = total,
                Items = pagedResidents
            });
        }

        /// <summary>
        /// 获取指定居民的详细信息
        /// </summary>
        /// <param name="id">居民ID</param>
        /// <returns>居民详细信息</returns>
        /// <response code="200">成功获取居民信息</response>
        /// <response code="404">指定ID的居民不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetResident(int id)
        {
            var resident = await _context.Residents.FindAsync(id);
            if (resident == null)
                return NotFound();

            return Ok(resident);
        }

        /// <summary>
        /// 创建新居民
        /// </summary>
        /// <param name="dto">居民信息</param>
        /// <returns>新创建的居民信息</returns>
        /// <response code="201">成功创建居民</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateResident(ResidentDTO dto)
        {
            var resident = new Resident
            {
                Name = dto.Name,
                Phone = dto.Phone,
                IdCard = dto.IdCard,
                Gender = dto.Gender,
                BirthDate = dto.BirthDate,
                Address = dto.Address,
                HouseId = dto.HouseId,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow,
                Password = HashPassword("123456")
            };

            _context.Residents.Add(resident);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetResident), new { id = resident.Id }, resident);
        }

        /// <summary>
        /// 更新居民信息
        /// </summary>
        /// <param name="id">居民ID</param>
        /// <param name="dto">更新的居民信息</param>
        /// <returns>更新后的居民信息</returns>
        /// <response code="200">成功更新居民信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的居民不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateResident(int id, ResidentDTO dto)
        {
            var resident = await _context.Residents.FindAsync(id);
            if (resident == null)
                return NotFound();

            resident.Name = dto.Name;
            resident.Phone = dto.Phone;
            resident.IdCard = dto.IdCard;
            resident.Gender = dto.Gender;
            resident.BirthDate = dto.BirthDate;
            resident.Address = dto.Address;
            resident.HouseId = dto.HouseId;
            resident.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(resident);
        }

        /// <summary>
        /// 删除指定居民
        /// </summary>
        /// <param name="id">居民ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除居民</response>
        /// <response code="404">指定ID的居民不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteResident(int id)
        {
            var resident = await _context.Residents.FindAsync(id);
            if (resident == null)
                return NotFound();

            _context.Residents.Remove(resident);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 修改居民密码
        /// </summary>
        /// <param name="id">居民ID</param>
        /// <param name="dto">密码修改信息</param>
        /// <returns>修改结果</returns>
        /// <response code="200">密码修改成功</response>
        /// <response code="400">密码修改失败</response>
        /// <response code="404">居民不存在</response>
        [HttpPost("{id}/change-password")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> ChangePassword(int id, ResidentChangePasswordDTO dto)
        {
            var resident = await _context.Residents.FindAsync(id);
            if (resident == null)
                return NotFound("居民不存在");

            // 验证原密码
            if (!VerifyPassword(dto.OldPassword, resident.Password))
                return BadRequest("原密码错误");

            // 更新密码
            resident.Password = HashPassword(dto.NewPassword);
            await _context.SaveChangesAsync();

            return Ok(new { message = "密码修改成功" });
        }

        private bool VerifyPassword(string password, string hashedPassword)
        {
            return HashPassword(password) == hashedPassword;
        }
    }
} 